package com.chen.utils.controller;

import cn.hutool.core.util.StrUtil;
import com.chen.root.enums.DriveEnum;
import com.chen.base.utils.JdbcUtil;
import com.chen.base.utils.StreamUtil;
import com.chen.root.base.PageData;
import com.chen.root.base.R;
import com.chen.utils.entity.DataSourceInfo;
import com.chen.utils.mapper.DataSourceInfoMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.List;

/**
 * @author: ~龙~
 * @date: 2023/7/20 14:32
 **/
@Slf4j
@RestController
@RequestMapping("/table")
@Api(tags = "表信息管理API")
public class TableController {

    @Resource
    private DataSourceInfoMapper dataSourceInfoMapper;

    @GetMapping("/page")
    @ApiOperation("分页获取表信息")
    public R<PageData<TableInfo>> tablePage(Integer currentPage, Integer pageSize,
                                            String tableName, String datasourceId){
        DataSourceInfo dsInfo = dataSourceInfoMapper.selectById(datasourceId);
        String sql = StrUtil.format(DriveEnum.getTableSql(dsInfo.getDataType()), dsInfo.getLibraryName());
        if (StrUtil.isNotBlank(tableName)){
            String tabName = "TABLE_NAME";
            if (DriveEnum.DB2.type.equalsIgnoreCase(dsInfo.getDataType())){
                tabName = "TABNAME";
            }else if (DriveEnum.KING_BASE8.type.equalsIgnoreCase(dsInfo.getDataType())){
                tabName = "t1.relname";
            }
            sql = StrUtil.format("{} AND {} LIKE '%{}%'", sql, tabName, tableName);
        }

        // 查询数据
        List<TableInfo> list = JdbcUtil.select(sql, dsInfo.getDataType(),
                dsInfo.getUrl(), dsInfo.getUsername(), dsInfo.getPassword(), TableInfo.class);
        long total = list.size();
        // stream分页
        list = StreamUtil.page(list, currentPage, pageSize);

        return R.ok(PageData.build(currentPage, pageSize, total, list),"");
    }

    /**
     * @author: Long
     * @date: 2023/7/18 20:36
     **/
    @Data
    public static class TableInfo implements Serializable {

        /**
         * 表名
         */
        private String tableName;

        /**
         * 表注释
         */
        private String tableComment;
    }
}
